<?php

namespace App\Models\Admin;

use App\Models\Api\StoreCart;
use Illuminate\Database\Eloquent\Model;

class StoreOrderGoods extends Model
{
    protected $fillable = [
        'order_id',
        'goods_id',
        'goods_number',
        'goods_price',
        'goods_amount',
        'is_give',
        'store_product_batch',
        'updated_at',
        'update_user',
        'store_id',
        'created_at',
        'create_user'
    ];

    protected $table = 'store_order_goods';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳

    /**
     * 获取订单商品列表
     */
    public static function getListByOid($order_id)
    {
        $list = self::from('store_order_goods as sg')
            ->select(['sg.*', 'c.cate_name', 'g.goods_specification', 'g.goods_unit', 'g.goods_sale_num', 'g.goods_price as goods_price_yu', 'g.goods_img', 'g.goods_sn', 'g.goods_name','g.goods_specification','g.id as goods_id','g.goods_unit','g.goods_weight_m'])
            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where(['sg.order_id' => $order_id])
            ->get();
        return $list;
    }

    public static function getVGByOid($order_id)
    {
        $list = self::from('store_order_goods as sg')
            ->select(['sg.goods_number', 'g.goods_name', 'g.goods_sale_num'])
            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
            ->where(['sg.order_id' => $order_id])
            ->get();
        return $list;
    }

    /**
     * 添加商品
     * @param $orderId
     * @param $data
     * @return mixed
     */
    public static function addInfoByOrderId($orderId, $storeId, $goodsList, $create_user = '')
    {
        if ($goodsList) {
            self::where(['order_id' => $orderId, 'store_id' => $storeId])->delete();
            foreach ($goodsList as $item) {
                $info = [];
                $info['order_id'] = $orderId;
                $info['store_id'] = $storeId;
                $info['goods_id'] = $item['goods_id'];
                $info['goods_price'] = $item['goods_price'];
                $info['goods_number'] = $item['goods_number'];
                if (empty($item['is_give']) || $item['is_give'] < 1) {
                    $info['goods_amount'] = $item['goods_price'] * $item['goods_number'];
                }
                $info['is_give'] = $item['is_give'];
                $info['remark'] = '补货';
                $info['created_at'] = time();
                $info['create_user'] = $create_user;

                self::insert(array_filter($info));
            }
        }
        return true;
    }
}